//
// @author				mitchell
// @description		020101.html页面的JS打包文件 注意引用顺序
// @lastmodified		$2010-7 - 15$
$(document).ready(function(){
	
	$(".tag").click(function(event){
		event.preventDefault();
		var tpye = $(this).attr("tpye");
		
		var tid = $(this).attr("tid");
		//改变选中与不选中的标签的颜色
		$(".tag").attr("class","menu_qb1 tag")
		$(this).attr("class","menu_qb tag");
		
		//隱藏所有列表
		$(".menu_list2").hide();
		//只顯示选中的标签的列表
		$(".tag_"+tid).show();
		
		if(tpye == 'all'){
			$(".menu_list2").show();
			return false;
		}
		
		//self.location = js_context.base_url+'store/'+sid+'#tag_'+tid;
	});
	
	/*****************点击下单**********************************/
	//引导层,注释掉了
	var layer = js_context.layer;
	$(".layer_"+layer).show();
	if($(".layer_"+layer).is(":visible")){
		var top = $(".get_food:first").offset().top;
		var left = $(".get_food:first").offset().left;
		var top1 = $(".guid_ss2").offset().top;
		var layer_top = $(".out_wk").offset().top;
		height = top-top1+layer_top;
		
		var html = '';
		var div = '';
		html = $(".get_food:first").html();
		fid = $(".get_food:first").attr('fid');
		$(".layer_food").html( html );
		$(".layer_food").mouseover(function(){
			$(".y_shop_"+fid).show();
			$(".layer_food").mouseleave(function(){
				$(".y_shop_"+fid).hide();
			});
		});
		$(".out_wk").css('top',height-10).css('left',-45);
	}
	
	//shopcar
	$(".gettel_button").click(function(event){//点击查看外卖电话按钮,获取商店电话
		event.preventDefault();
		$(".gettel_load").show();
		var _this = this;
		var sid = $(_this).attr('sid');
		var url = js_context.base_url+"ajax/store/placeorder_gettel";
		$.get(url,{'sid' : sid}, function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			$(".gettel_button,.gettel_load").hide();
			var data = result.message;
			//$(".report_tel").hide();
			$(".store_tel").html(data);
			$(".cart-tel").show();
			$(_this).hide();
			
			if(!result.login){
				var layer = result.layer.js_layer;
				if(!result.layer.layer){
					layer_div = $(".layer_"+layer).show();
					var st = $(document).scrollTop();
					$(".layer_"+layer+":first").css('top',st-20).css('left',-70);
					$("."+layer).click(function(event){
						event.preventDefault();
						var _this = this;
						var type = $(".layer_"+layer).attr("type");
						var url =js_context.base_url+"ajax/account/pic_layer";
						$.get(url,{"type" : type}, function(result){
							if(result.success == false){
								alert('通讯失败');
								return false;
							}
							$(".out_wk,.layer_"+layer+", .layer1_"+layer).hide();
						},"json");
					});
				}
			}
			
		},"json");
		return false;
	});
	
	$(".placeorder").click(function(event){
		event.preventDefault();
		$(".gettel_load").show();
		var sid = $(this).attr('sid');
		var price = $(".all_price").html();
		var min =$(".cart-mini .mincost").html();
        var  s = price.replace(/[^0-9]/ig,"");
        var t = min.replace(/[^0-9]/ig,"");
        if( Number(s) < Number(t)){
        	alert("没有达到最低消费");
        	return false;
        }
        if(!$(".cart-xiadan").is(":hidden")){ 
        	alert("请您先购物！");
			return false;
		}
		var url = js_context.base_url+"ajax/store/placeorder";
		$.get(url,{'sid' : sid}, function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			$(".gettel_load").hide();
			var data = result.message;
			//layer
			if(result.login == 'n'){
				var layer = result.layer.js_layer;
				if(!result.layer.layer){
					layer_div = $(".layer_"+layer).show();
					var st = $(document).scrollTop();
					$(".layer_"+layer+":first").css('top',st-20).css('left',-70);
					$("."+layer).click(function(event){
						event.preventDefault();
						var _this = this;
						var type = $(".layer_"+layer).attr("type");
						var url =js_context.base_url+"ajax/account/pic_layer";
						$.get(url,{"type" : type}, function(result){
							if(result.success == false){
								alert('通讯失败');
								return false;
							}
							$(".out_wk,.layer_"+layer+", .layer1_"+layer).hide();
							/*******/
							if(data == 'n'){
								var st = $(document).scrollTop();
								$("#jiesuan-bu").css("margin-top",st-50).show(); 
								return false;
							}
							self.location = js_context.base_url+'shopcar/setup_order?sid='+sid;
							/*******/
						},"json");
					});
				}
				/*******/
				if(data == 'n'){
					var st = $(document).scrollTop();
					$("#jiesuan-bu").css("margin-top",st-50).show(); 
					return false;
				}
				self.location = js_context.base_url+'shopcar/setup_order?sid='+sid;
				/*******/
				return false;
			}
			
			var data = result.message;
			if(data == 'n'){
				var st = $(document).scrollTop();
				$("#jiesuan-bu").css("margin-top",st-50).show(); 
				return false;
			}
			self.location = js_context.base_url+'shopcar/setup_order?sid='+sid;
			
		},"json");
		return false;
	});
	
	//下单按钮,已经注释
	$(".tj_shopcar").click(function(event){
		event.preventDefault();
		var sid = $(this).attr('sid');
		var price = $(".all_price").html();
		var min =$(".cart-mini .mincost").html();
        var  s = price.replace(/[^0-9]/ig,"");
        if(min){
	        var t = min.replace(/[^0-9]/ig,"");
	        if( Number(s) < Number(t)){
	        	alert("没有达到最低消费");
	        	return false;
	        }
	        if(!$(".cart-xiadan").is(":hidden")){ 
	        	alert("请您先购物！");
				return false;
			}
        }else{
        	 if(!$("#shoparr").val()){ 
             	alert("请您先购物！");
     			return false;
     		}
        }
       
        
        var url = js_context.base_url+"ajax/store/check_store";
        $.get(url, {}, function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			//登录状态
			if(data == 0 && !result.login){
				self.location = js_context.base_url+'shopcar/setup_order';
				return false;
			}
			
			//1 、没签约     2、签约和没签约  3、签约
			if(data == 1 || result.login){
				//TODO thickbox
				$(".thickbox").attr("typeid","box");
				var datainfo = result.value;
				var html = '';
				var priceall = 0;
				var price = 0;
				var price1 = 0;
				var price2 = 0;
				for(var i=0;i<datainfo.length;i++){
					if(datainfo[i].servecost==0 || $.trim(datainfo[i].servecost)==null || $.trim(datainfo[i].servecost)=="免费"){
						price1 += 0;
					}else{
						//html += +parseInt(data[i].servecost)+'元';
						price2 += parseInt(datainfo[i].servecost);
					}
					html += '<div class="dish-list1">';
					html += '<h3>'+datainfo[i].storename+'<span>电话：<font>'+datainfo[i].tel+'</font></span><span>送餐费：<font>'+datainfo[i].servecost+'</font></span></h3>';
					html += '<div class="dish-list2">';
					html += '<div id="dish-list2">';
					html +=	'<div id="dish-list2-name">菜名</div>';
					html +=	'<div id="dish-list2-price">单价</div>';
					html +=	'<div id="dish-list2-num">数量</div>';
					html += '</div>';
					
					var food = datainfo[i].food;
					var x=0;
					for(x=0;x<food.length;x++){
						html += '<div class="dish-list3">';
						html +=	'<div class="dish-list3-name"><a href="'+js_context.base_url+'food/'+food[x].fid+'" title="'+food[x].foodname+'">'+food[x].foodname.substr(0,16)+'</a></div>';
						html +=	'<div class="dish-list3-price">'+food[x].price+'</div>';
						html +=	'<div class="dish-list3-num">'+food[x].count+'</div>';
						html += '</div>';
						priceall += food[x].price*food[x].count;
					}
					html += '</div>';
					html += '</div>';
				}
				$(".orderArr").html(html);
				$("#allprice").html(price1+price2+priceall);
				$(".cart-ifact").html('');
				$(".cart-xiadan").show();
				//header 
				$(".shopcar_list").html('');
				$(".header_shopcar_num").html("0");
				$(".word").html("您的购物车没有任何商品");
				$(".all_price").html('总计：￥0.00元');
				imgLoader = new Image();// preload image
		    	imgLoader.src = tb_pathToImage;
				tb_init('a.thickbox, area.thickbox, input.thickbox,.thickbox');//pass where to apply thickbox
				

				var height = $("#order_div").height(); 
				$("#TB_window").css('height',height+100);
				return false;
			}
			if(data == 2){
				self.location = js_context.base_url+'shopcar/setup_order';
				return false;
			}
			if(data == 3){
				var st = $(document).scrollTop();
				$("#jiesuan-bu").css("margin-top",st-50).show(); 
				return false;
			}
        },"json");
        
      //self.location = js_context.base_url+'shopcar/setup_order';
	});
	
	//提交订单悬浮框
	$(document).keyup(function(e){
		if(e.which == 27){
			var temp= $("#jiesuan-bu").is(":visible");//是否可见
			if(!temp){
				return false;
			}
			$("#jiesuan-bu").hide();
		}
	});
	
	$(".xf_close").click(function(event){
		event.preventDefault();
		$("#jiesuan-bu").hide();
	});
	
	//提交订单时的手机验证
	var count= $('#number').html();
    function BtnCount() {
           if (count == 0) {
        	$(".phone-check-ccc100").hide();
        	$(".phone-check100").attr("disabled","").show();
        	$('#number').html(60);
        	$(".tishi").show();
        	$(".randnum_ts").hide();
            clearTimeout(BtnCount);   // 可取消由 setTimeout() 方法设置的 timeout
           }else {
            count--;
            $('#number').html(count);
            setTimeout(BtnCount, 1000); 
        }
    };
    
	$(".get_randnum").click(function(event){
		event.preventDefault();
		var _this = this;
		var tel = $.trim($("#tel").val());
		var url = js_context.base_url+"ajax/reg/check_tel_in";
		$(".rend_load").show();
		if(!tel){
			$(".rend_load").hide();
			$(_this).attr("disabled", "");
			alert("手机不能为空");
			return false;
		}
		var myreg = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
		if( !myreg.test(tel)){
			$(".rend_load ").hide();
			$(_this).attr("disabled", "");
			 alert("请你认真填写手机号码");
			 return false; 
		}
		$(this).attr("disabled", "true");
		$.get(url, {'tel' : tel}, function(result){
			$(".rend_load").hide();
			if(result.success == false){
				alert('通讯失败');
				
				return false;
			}
			$(_this).attr("disabled","");
			var data = result.message;
			if(data=='tel' ){
				$(".rend_load").hide();
				alert("手机号码已 被注册！请在右边登录");
				return false;
			}
			
			if(data=='in' && !confirm('手机已存在,可能覆盖之前手机')){
				$(_this).attr("disabled","");
				$(".rend_load").hide();
				return false;
			}
			
			$(_this).attr("disabled","");
				
				/*********************/
				var url_t = js_context.base_url+"ajax/reg/get_tel_randnum";
				$.get(url_t, {'tel' : tel}, function(result){
					$(".rend_load").hide();
					$(".tishi").hide();
					if(result.success == false){
						alert('通讯失败');
						return false;
					}
					var data = result.message;
//					if(result.data == 'same'){
//						alert("手机已经验证");
//						$(".phone-check").hide();
//						$(this).attr("disabled", "true");
//						$(".randnum").attr("disabled", "true");
//						$("#insert").val("y");
//						$(".phone-check").attr("disabled","");
//						$(".randnum").attr("disabled", "true");
//						return false;
//					}

					if(!data){
						alert("验证码已经发送，请您耐心等待");
						$(".phone-check-ccc100").attr("disabled","true").show();
						$(".phone-check100").hide();
					}else{
						alert("验证码已经发送，请您耐心等待");
						$(".phone-check-ccc100").attr("disabled","true").show();
						$(".phone-check100").hide();
					}

					$(".randnum_ts").show();
					$(".tishi").hide();
					var temp= $(".randnum_ts").is(":visible");//是否可见
					if(!temp){
						return false;
					}else{
						  var timeout;
					      timeout = setTimeout(BtnCount, 1000);
					}
				},"json");
				/*********************/
		},"json");
	
	});
	
	//reg button
	$('#reg_button').click(function(event){
		event.preventDefault();
		var sid = $(this).attr("sid");
		var username = $.trim($("#username").val());
		var email = $.trim($("#email").val());
		var address = $.trim($("#address").val());
		var tel = $.trim($("#tel").val());
		var randnum = $.trim($("#randnum").val());
		var remarks = $.trim($("#remarks").val());
		var url = js_context.base_url+"ajax/reg/reg_order";
		if(username == ""){
			alert("收货人姓名不能为空！")
			return false;
		}
		if(email == ""){
			alert("邮箱不能为空！")
			return false;
		}
		if(address == ""){
			alert("收货人地址不能为空！")
			return false;
		}
		if(tel == ""){
			alert("联系人手机不能为空！")
			return false;
		}
		var myreg = /^0?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/;
		if( !myreg.test(tel)){
			$(".rend_load ").hide();
			 alert("请你认真填写手机号码");
			 return false; 
		}
		if(randnum == ""){
			alert("手机验证码不能为空！")
			return false;
		}
		$.get(url,{"username" : username,"email" : email,"address":address,"tel":tel,"randnum":randnum,"remarks":remarks},function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(result.error){
				alert("验证码错误！请重新输入");
				return false;
			}
			
			if(data == 'tel'){
				alert('手机号码已 被注册！请在右边登录');
				return false;
			}
			self.location = js_context.base_url+'shopcar/place_order?ucid='+data+'&sid='+sid+'&remarks='+remarks;
			//self.location = js_context.base_url+'shopcar/setup_order?sid='+sid;
		},"json"); 
	});
	//提交订单时的login
	$("#user").blur(function(event){
		var value = $.trim($(this).val());
		if(!value){
			$(this).val("也可以用昵称或手机号码登录");
		}
	});
	
	$("#login_button").click(function(event){
		event.preventDefault();
		var sid = $(this).attr("sid");
		var url = js_context.base_url+"ajax/account/login";
		var email = $.trim($("#user").val());
		var password = $.trim($("#psd").val());
		if(email == '' || email == '也可以用昵称或手机号码登录'){
			alert("请输入帐号");
			return false;
		}
		if(password == ''){
			alert("请输入密码");
			return false;
		}
		
		$.get(url,{ "email" : email,"password" :password }, function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			var error = result.error;
			if(!data){
				alert('登录失败');
				return false;
			}
			if(error==1){
				alert("密码错误，请重新输入");
				return false;
			}
			if(error==2){
				alert("帐号错误，请重新输入");
				return false;
			}
			self.location = js_context.base_url+'shopcar/setup_order?sid='+sid;
		},"json");
	});
	//验证码吧
	$("#randnum").blur(function(){
		var data = $(this).val();
		var tel = $("#tel").val();
		var url = js_context.base_url+"ajax/reg/check_tel_randnum";
		if(data.length==6){
			$.get(url, {'data' : data, 'tel' : tel}, function(result){
				if(result.success == false){
					alert('通讯失败');
					return false;
				}
				var info = result.message;
				if(info == "in"){
					$(".yes").show();
					$(".no").hide();
					return false;
				}
				$(".yes").hide();
				$(".no").show();
				return false;
			},"json");
			$(".yes").hide();
			$(".no").show();	
			return false;
		}
		$(".yes").hide();
		$(".no").show();	
	})
	
	$("#email").keypress( function(e) {
		var key = window.event ? e.keyCode : e.which;
		if(key.toString() == "13"){
			var email = $.trim($("#email").val());
			if(!email){
				$(".email,.email_n").show();
				$(".email_y").hide();
				return false;
			}
			$(".email").hide();
		}
	});
	
	$('#email').blur(function(){
		var email = $.trim($("#email").val());
		if(email == ""){
			$('.email,.email_n').show();
			$('.email_y').hide();
			$('.reg_button').attr("disabled", "true");
			return false; 
		}else{
			var myreg = /^[a-zA-Z0-9._%-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{1,4}$/;
			 if(!myreg.test(email)){
				 $('.email,.email_n').show();
				 $('.email_y').hide();
				 $('.reg_button').attr("disabled", "true");
				 return false; 
			 }
			 $('.email,.email_n,.email_y').hide();
			 $('.reg').attr("disabled", "");
		}
		var url = js_context.base_url+"ajax/reg/check_reg";
		var type = $(this).attr("types");
		$.get(url,{"typeid" : email,"type":type},function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(data){
				$(".c_email,.email_n").show();
				return false;
			}
			$(".c_email").hide();
			$(".email_y").show();
		},"json"); 
	});
	
	$("#username").keypress( function(e) {
		var key = window.event ? e.keyCode : e.which;
		if(key.toString() == "13"){
			var username = $("#username").val();
			if(!username){
				$(".username").show();
				return false;
			}
			$(".username").hide();
		}
	});
	/*****************************************************************************/
	//tag list
	$(".tag_list").click(function(event){
		event.preventDefault();
		var div = $(this).attr("type");
		$(".tag_list").show();
		$("."+div).hide();
		if(div == "yc"){
			$(".store-list-b").slideUp(800);
		}else{
			$(".store-list-b").slideDown(800);
		}
	});
	//food list
	$(".food_list").click(function(event){
		event.preventDefault();
		var _this = this;
		var div = $(_this).attr("type");
		var tid = $(_this).attr("tid");
		$(_this).hide();
		$("."+div+"_"+tid).show();
		$(".food_"+tid+" ,.ul_"+tid).toggle(800);
	});
	
	$(".menu_rjt").click(function(event){
		event.preventDefault();
		$(".menu_ts,#mask").hide();
	});
	$(document).keyup(function(e){
		if(e.which == 27){
			var temp= $(".menu_ts").is(":visible");//是否可见
			if(!temp){
				return false;
			}
			$(".menu_ts,#mask").hide();
		}
	});
	
	var tb_pathToImage = js_context.base_url+"res/images/loadingAnimation.gif";
	var store_close = js_context.close;
	if(store_close){
		imgLoader = new Image();// preload image
		imgLoader.src = tb_pathToImage;
		tb_init('a.thickbox, area.thickbox, input.thickbox,.thickbox');//pass where to apply thickbox
	}
	/*
	 * 12.02.06
	 */
	//加入收藏
	$(".collect").click(function(event){
		event.preventDefault();
		$(".collect_load").show();
		var url = js_context.base_url+"ajax/user/collect";
		var _this = this;
		var op = $(this).attr('op');
		var statid = $(this).attr('ustatid');
		$(_this).attr("disabled", "true");
		$.get(url, {'op' : op, 'statid': statid,'id':$(this).attr('sid'), 'type':$(this).attr('typeid')}, function(result){
			$(".collect_load").hide();
			$(_this).attr("disabled", "");
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(data['data'] == 'error'){
				alert('操作失败');
				return false;
			}
			if(data['data'] == 'notlogin'){
				alert('请先登录');
				return false;
			}
			if(op == 'del'){
				$(_this).attr('class','collect store_sc').show();
				$(_this).attr('op','add');
				$(_this).attr('title','收藏本店');
			}
			
			if(op == 'add'){
				$(_this).attr('ustatid',result.ustatid);
				$(_this).attr('class','collect awu').show();
				$(_this).attr('title','取消收藏');
				$(_this).attr('op','del');
			}
		},"json");
	});
	//order
	$("#sales").mouseover(function(event){
		event.preventDefault();
		$('#sales .default_order').show();
	});
	
	$("#sales").mouseleave(function(){
		$('#sales .default_order').hide();
	});
	//菜单鼠标滑过 显示加入购物车
	$(".meal-1").bind('mouseenter',function(event){
		event && event.preventDefault();
		var _this = this;
		var overclass;
		$(this).find('.jiagou').show().bind('mouseenter',function(event){
			event && event.preventDefault();
			return false;
		});
		
		$(".meal-1").bind('mouseleave',function(event){
			event && event.preventDefault();
			$(_this).find('.jiagou').hide();
			return false;
		});
		return false;
	});
	//report
	$(".report").click(function(event){
		event.preventDefault();
		$(".edit_tel").show();
	});
	
	$(".r_tel").blur(function(){
		var data = $.trim($(this).val());
		if(data==''){
			$(this).val('请输入电话');
		}
	});
	//电话纠错
	$(".dd_jb").click(function(event){
		event.preventDefault();
		var sid = $(this).attr("sid");
		var url = js_context.base_url+"ajax/store/insert_report";
		$.get(url,{'sid' : sid},function(result){
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(!data){
				alert('操作失败');
				return false;
			}
			if(data['error'] == 'timeout'){
				alert('请您半小时后再举报！');
				$(".edit_tel,.report_tel").hide();
				return false;
			}

			$('.report_tel').show();
		},"json");
	});
	
	$(".inputjiu").click(function(event){
		event.preventDefault();
		var tel = $(".r_tel").val();
		var sid = $(".r_tel").attr("sid");
		var url = js_context.base_url+"ajax/store/reporttel";
		$('.report_load').show();
		if(tel==''||tel=='请输入电话'){
			$('.report_load').hide();
			alert("请输入电话");
			$('.r_tel').focus();
			return false; 
		}
		var myreg = /^[-\d]+$/;
		if(!myreg.test(tel) || tel.length < 8){
			$('.report_load').hide();
			alert("您输入的电话有误！");
			return false; 
		}
		$.get(url, {'tel' : tel,'sid' : sid}, function(result){
			$('.report_load').hide();
			if(result.success == false){
				alert('通讯失败');
				return false;
			}
			var data = result.message;
			if(!data){
				alert('操作失败');
				return false;
			}
			if(data['error'] == 'notlogin'){
				alert('请先登录');
				$(".edit_tel,.report_tel").hide();
				return false;
			}
			if(data['error'] == 'timeout'){
				alert('请您半小时后再提交！');
				$(".edit_tel,.report_tel").hide();
				return false;
			}
			alert("提交成功！谢谢您的参与");
			$(".edit_tel,.report_tel").hide();
		},"json")
	});
	
	var s_type = js_context.s_type;
	if(s_type=='s_content'){
		function creat_map(latitude,longitude){
			var latlng = new google.maps.LatLng(latitude,longitude);
			var myOptions = {
				    zoom: 16,
				    center: latlng,
				    mapTypeId: 'roadmap',
				    mapTypeControl:false,
				    streetViewControl:false,
				    navigationControl:false
			};
			var map = new google.maps.Map(document.getElementById("map"), myOptions);
			var marker = new google.maps.Marker({
		 		map: map,
		 		position: latlng
		    });
		}
		//instance create map...
		creat_map(js_context.lat,js_context.lng);
	}
	//shopcar
	/*
	var shopcarnum = js_context.shopcarnum;
	var isIE=!!window.ActiveXObject;
	var isIE6 = isIE&&!window.XMLHttpRequest;
	if(isIE6){
		return false;
	}
	var shopcar_box = $("#shopcar_box");
	trip_shopcar = function() {
        var st = $(document).scrollTop();
        var width = $(window).width()/2 + 155;
        if(st > 195){
        	$("#huidingbu").show();
        	if(shopcarnum == 0)
        		$(".shop_order_big").attr("class","cartc").hide();
        	else
        		$(".shop_order_big").attr("class","cartc");
			shopcar_box.css("left", width);
        }else{
        	if(shopcarnum == 0)
        		$(".cartc").attr("class","shop_order_big").hide();
        	else
        		$(".cartc").attr("class","shop_order_big");
        	$("#huidingbu").hide();
        }
    };
  
    $(window).bind("scroll", trip_shopcar);
  */
    $(".ret_top").click(function(){
	   $('html,body').animate({ scrollTop:0 },1000);
	   return false;
    });
    /******************************************************************************/
    
    //var tb_pathToImage = js_context.base_url+"res/images/loadingAnimation.gif";
    /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/
    function tb_init(domChunk){
    	//$(domChunk).click(function(){
    	if($(domChunk).attr("typeid") == "box"){
    		var t = $(domChunk).attr('title') || $(domChunk).attr('name') || null;
    		var a = $(domChunk).attr('href')|| $(domChunk).attr('alt');
    		var g = $(domChunk).attr('rel')|| false;
    		tb_show(t,a,g);
    		$(domChunk).blur();
    		return false;
    	}
    	//});
    }

    function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

    	try {
    		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
    			$("body","html").css({height: "100%", width: "100%"});
    			$("html").css("overflow","hidden");
    			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
    				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
    				$("#TB_overlay").click(tb_remove);
    			}
    		}else{//all others
    			if(document.getElementById("TB_overlay") === null){
    				$("body").append("<div id='TB_overlay' style='z-index:300'></div><div id='TB_window' style='z-index:1000'></div>");
    				$("#TB_overlay").click(tb_remove);
    			}
    		}
    		
    		if(tb_detectMacXFF()){
    			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
    		}else{
    			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
    		}
    		
    		if(caption===null){caption="";}
    		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
    		$('#TB_load').show();//show loader
    		
    		var baseURL;
    	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
    			baseURL = url.substr(0, url.indexOf("?"));
    	   }else{ 
    	   		baseURL = url;
    	   }
    	   
    	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
    	   var urlType = baseURL.toLowerCase().match(urlString);

    		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
    				
    			TB_PrevCaption = "";
    			TB_PrevURL = "";
    			TB_PrevHTML = "";
    			TB_NextCaption = "";
    			TB_NextURL = "";
    			TB_NextHTML = "";
    			TB_imageCount = "";
    			TB_FoundURL = false;
    			if(imageGroup){
    				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
    				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
    					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
    						if (!(TB_TempArray[TB_Counter].href == url)) {						
    							if (TB_FoundURL) {
    								TB_NextCaption = TB_TempArray[TB_Counter].title;
    								TB_NextURL = TB_TempArray[TB_Counter].href;
    								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
    							} else {
    								TB_PrevCaption = TB_TempArray[TB_Counter].title;
    								TB_PrevURL = TB_TempArray[TB_Counter].href;
    								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
    							}
    						} else {
    							TB_FoundURL = true;
    							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
    						}
    				}
    			}

    			imgPreloader = new Image();
    			imgPreloader.onload = function(){		
    			imgPreloader.onload = null;
    				
    			// Resizing large images - orginal by Christian Montoya edited by me.
    			var pagesize = tb_getPageSize();
    			var x = pagesize[0] - 150;
    			var y = pagesize[1] - 150;
    			var imageWidth = imgPreloader.width;
    			var imageHeight = imgPreloader.height;
    			if (imageWidth > x) {
    				imageHeight = imageHeight * (x / imageWidth); 
    				imageWidth = x; 
    				if (imageHeight > y) { 
    					imageWidth = imageWidth * (y / imageHeight); 
    					imageHeight = y; 
    				}
    			} else if (imageHeight > y) { 
    				imageWidth = imageWidth * (y / imageHeight); 
    				imageHeight = y; 
    				if (imageWidth > x) { 
    					imageHeight = imageHeight * (x / imageWidth); 
    					imageWidth = x;
    				}
    			}
    			// End Resizing
    			
    			TB_WIDTH = imageWidth + 30;
    			TB_HEIGHT = imageHeight + 60;
    			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>关闭</a> or Esc键</div>"); 		
    			
    			$("#TB_closeWindowButton").click(tb_remove);
    			
    			if (!(TB_PrevHTML === "")) {
    				function goPrev(){
    					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
    					$("#TB_window").remove();
    					$("body").append("<div id='TB_window'></div>");
    					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
    					return false;	
    				}
    				$("#TB_prev").click(goPrev);
    			}
    			
    			if (!(TB_NextHTML === "")) {		
    				function goNext(){
    					$("#TB_window").remove();
    					$("body").append("<div id='TB_window'></div>");
    					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
    					return false;	
    				}
    				$("#TB_next").click(goNext);
    				
    			}

    			document.onkeydown = function(e){ 	
    				if (e == null) { // ie
    					keycode = event.keyCode;
    				} else { // mozilla
    					keycode = e.which;
    				}
    				if(keycode == 27){ // close
    					tb_remove();
    				} else if(keycode == 190){ // display previous image
    					if(!(TB_NextHTML == "")){
    						document.onkeydown = "";
    						goNext();
    					}
    				} else if(keycode == 188){ // display next image
    					if(!(TB_PrevHTML == "")){
    						document.onkeydown = "";
    						goPrev();
    					}
    				}	
    			};
    			
    			tb_position();
    			$("#TB_load").remove();
    			$("#TB_ImageOff").click(tb_remove);
    			$("#TB_window").css({display:"block"}); //for safari using css instead of show
    			};
    			
    			imgPreloader.src = url;
    		}else{//code to show html
    			
    			var queryString = url.replace(/^[^\?]+\??/,'');
    			var params = tb_parseQuery( queryString );

    			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
    			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
    			ajaxContentW = TB_WIDTH - 30;
    			ajaxContentH = TB_HEIGHT - 45;
    			
    			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
    					urlNoQuery = url.split('TB_');
    					$("#TB_iframeContent").remove();
    					if(params['modal'] != "true"){//iframe no modal
    						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>关闭</a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
    					}else{//iframe modal
    					$("#TB_overlay").unbind();
    						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
    					}
    			}else{// not an iframe, ajax
    					if($("#TB_window").css("display") != "block"){
    						if(params['modal'] != "true"){//ajax no modal
    						$("#TB_window").append("<div id='TB_title' class='menu_bt'><div class='menu_ljt'></div><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' style='color:#000000'>关闭</a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
    						}else{//ajax modal
    						$("#TB_overlay").unbind();
    						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
    						}
    					}else{//this means the window is already up, we are just loading new content via ajax
    						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
    						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
    						$("#TB_ajaxContent")[0].scrollTop = 0;
    						$("#TB_ajaxWindowTitle").html(caption);
    					}
    			}
    					
    			$("#TB_closeWindowButton").click(tb_remove);
    			
    				if(url.indexOf('TB_inline') != -1){	
    					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
    					$("#TB_window").unload(function () {
    						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
    					});
    					tb_position();
    					$("#TB_load").remove();
    					$("#TB_window").css({display:"block"}); 
    				}else if(url.indexOf('TB_iframe') != -1){
    					tb_position();
    					if($.browser.safari){//safari needs help because it will not fire iframe onload
    						$("#TB_load").remove();
    						$("#TB_window").css({display:"block"});
    					}
    				}else{
    					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
    						tb_position();
    						$("#TB_load").remove();
    						tb_init("#TB_ajaxContent a.thickbox");
    						$("#TB_window").css({display:"block"});
    					});
    				}
    			
    		}

    		if(!params['modal']){
    			document.onkeyup = function(e){ 	
    				if (e == null) { // ie
    					keycode = event.keyCode;
    				} else { // mozilla
    					keycode = e.which;
    				}
    				if(keycode == 27){ // close
    					tb_remove();
    				}	
    			};
    		}
    		
    	} catch(e) {
    		//nothing here
    	}
    }

    //helper functions below
    function tb_showIframe(){
    	$("#TB_load").remove();
    	$("#TB_window").css({display:"block"});
    }

    function tb_remove() {
     	$("#TB_imageOff").unbind("click");
    	$("#TB_closeWindowButton").unbind("click");
    	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
    	$("#TB_load").remove();
    	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    		$("body","html").css({height: "auto", width: "auto"});
    		$("html").css("overflow","");
    	}
    	document.onkeydown = "";
    	document.onkeyup = "";
    	return false;
    }

    function tb_position() {
    $("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
    	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
    	}
    }

    function tb_parseQuery ( query ) {
       var Params = {};
       if ( ! query ) {return Params;}// return empty object
       var Pairs = query.split(/[;&]/);
       for ( var i = 0; i < Pairs.length; i++ ) {
          var KeyVal = Pairs[i].split('=');
          if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
          var key = unescape( KeyVal[0] );
          var val = unescape( KeyVal[1] );
          val = val.replace(/\+/g, ' ');
          Params[key] = val;
       }
       return Params;
    }

    function tb_getPageSize(){
    	var de = document.documentElement;
    	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    	arrayPageSize = [w,h];
    	return arrayPageSize;
    }

    function tb_detectMacXFF() {
      var userAgent = navigator.userAgent.toLowerCase();
      if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
        return true;
      }
    }
  
});
